package com.aiti.lulian.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.aiti.base.core.base.service.iml.BaseSerivceImpl;
import com.aiti.base.core.utils.message.Message;
import com.aiti.lulian.dto.CardContractCollaboratorDto;
import com.aiti.lulian.entity.CardBusinessContract;
import com.aiti.lulian.entity.CardContractCollaborator;
import com.aiti.lulian.feign.CloudShowManagerSubService;
import com.aiti.lulian.mapper.CardContractCollaboratorMapper;
import com.aiti.lulian.service.CardBusinessContractService;
import com.aiti.lulian.service.CardContractCollaboratorService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service
public class CardContractCollaboratorServiceImpl extends BaseSerivceImpl<CardContractCollaboratorMapper, CardContractCollaborator> implements CardContractCollaboratorService {
    @Autowired
    private CardBusinessContractService contractService;
    @Autowired
    private CloudShowManagerSubService cloudShowManagerSubService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Message dealCollaborator(CardContractCollaboratorDto dto) {
        String op = dto.getOp();
        List<String> idList = dto.getIdList();
        List<String> userIdList = dto.getUserIdList();
        List<String> errorList = new ArrayList();
        if(!"3".equals(op)){
            //添加或修改
            if(!CollectionUtil.isEmpty(idList)){



                if(!CollectionUtil.isEmpty(userIdList)){
                    String collactorIds = String.join(",", userIdList);
                    Message userMessage = cloudShowManagerSubService.getUserList(collactorIds);
                    if(userMessage == null || userMessage.getCode() == 1){
                        throw new RuntimeException("员工信息获取失败");
                    }

                    List<LinkedHashMap> userInfoList = (List<LinkedHashMap>)userMessage.getObj();
                    if(userInfoList != null && !userInfoList.isEmpty()){
                        Map<Object, LinkedHashMap> userMap = userInfoList.stream().collect(Collectors.toMap(k ->
                                        k.get("baseId"),
                                v -> v,
                                (existing, replacement) -> existing
                        ));
                        List collactorList = new ArrayList();

                        for (String baseId : idList){
                            List<String> shouldOverrideIdLit = new ArrayList<>();
                            CardBusinessContract contract = contractService.getById(baseId);
                            if("1".equals(op)){

                                List<CardContractCollaborator> existList = this.list(new LambdaQueryWrapper<CardContractCollaborator>().eq(CardContractCollaborator::getRelateId, baseId));
                                if(!CollectionUtils.isEmpty(existList)){
                                    List<String> existUserIdList = existList.stream().map(m -> m.getUserId()).collect(Collectors.toList());
                                    existUserIdList.forEach(f->{
                                        if(userIdList.contains(f)){
                                            errorList.add("合同名称为："+contract.getBaseName()+"所选的协作人："+userMap.get(f).get("realname")+"已经是该合同的协作人了，请重新选择");
                                        }
                                    });
                                    userIdList.removeAll(existUserIdList);
                                }
                            }

                            String directorId = contract.getDirectorId();
                            for (String userId : userIdList){
                                if(!userId.equals(directorId)){
                                    LinkedHashMap map = userMap.get(userId);
                                    CardContractCollaborator CardContractCollaborator = new CardContractCollaborator();
                                    CardContractCollaborator.setCompanyId(map.get("companyId") == null ? "" : map.get("companyId").toString());
                                    CardContractCollaborator.setUserId(userId);
                                    CardContractCollaborator.setRelateId(baseId);
                                    CardContractCollaborator.setUserName(map.get("realname") == null ? "" : map.get("realname").toString());
                                    CardContractCollaborator.setDeptId(map.get("deptId") == null ? "" : map.get("deptId").toString());
                                    collactorList.add(CardContractCollaborator);
                                    if("2".equals(op)){
                                        shouldOverrideIdLit.add(userId);
                                    }

                                }else{

                                    errorList.add("合同名称为："+contract.getBaseName()+"所选的协作人："+userMap.get(userId).get("realname")+"是合同负责人，请重新选择");
                                }

                            }
                            if("2".equals(op) && !CollectionUtils.isEmpty(shouldOverrideIdLit)){
                                this.remove(new LambdaQueryWrapper<CardContractCollaborator>().eq(CardContractCollaborator::getRelateId,baseId));
                            }
                        }
                        if(!CollectionUtils.isEmpty(collactorList)){
                            this.saveBatch(collactorList);
                        }
                    }

                }

            }


        }else{
            //删除
            if(!CollectionUtil.isEmpty(idList)){
                for (String relateId : idList){
                    this.remove(new LambdaQueryWrapper<CardContractCollaborator>().eq(CardContractCollaborator::getRelateId,relateId).in(CardContractCollaborator::getUserId,userIdList));
                }
            }


        }
        if(!CollectionUtil.isEmpty(errorList)){
            return Message.fail(errorList);
        }else{
            return Message.success();
        }

    }
}
